/*
 * @Author: WuFeng <763467339@qq.com>
 * @Date: 2024-11-13 13:06:07
 * @LastEditTime: 2024-11-13 23:24:43
 * @LastEditors: WuFeng <763467339@qq.com>
 * @Description: pdf 通用方法
 * @FilePath: \markdown-magic\src\pages\Pdf\service\common.js
 * @Copyright 版权声明
 */
import * as pdfjsLib from "pdfjs-dist"
import * as workerSrc from "pdfjs-dist/build/pdf.worker.min?url"

import * as mammoth from "mammoth"

import { textToArrayBuffer } from '@/utils/index.js'

// 配置 PDF.js worker 的路径
pdfjsLib.GlobalWorkerOptions.workerSrc = workerSrc.default

// pdf 转图片 base64
export async function pdfToBase64(arrayBuffer) {
  try {

    // 使用 pdfjs-dist 加载 PDF 文档
    const loadingTask = pdfjsLib.getDocument({data: arrayBuffer});
    const pdf = await loadingTask.promise;
    
    // console.log(`🚀 ~ pdfToBase64 ~ pdf:`, pdf)

    const pdfResult = []

    for (let i = 0; i< pdf.numPages; i++) {

      const pageNumber = i + 1
      // 获取指定页面
      const page = await pdf.getPage(pageNumber)
  
      // 获取页面尺寸
      const viewport = page.getViewport({ scale: 1.5 })
  
      // 创建画布
      const canvas = document.createElement('canvas')
      canvas.width = viewport.width
      canvas.height = viewport.height
      const context = canvas.getContext('2d')
  
      // 渲染页面到画布
      const renderContext = {
        canvasContext: context,
        viewport: viewport
      }
      await page.render(renderContext).promise
  
      // 将画布内容转换为 Base64 编码的图片
      const base64Image = canvas.toDataURL('image/png')
  
      // return base64Image
      pdfResult.push(base64Image)
    }

    return new Promise((resolve, reject) => {
      resolve(pdfResult)
    })

    

  } catch (error) {
    console.error('Error converting PDF page to base64 image:', error);
    throw error;
  }
}

// pdf 某一页转图片 base64
export async function pdfPageToBase64(arrayBuffer, pageNumber) {
  try {

    // 使用 pdfjs-dist 加载 PDF 文档
    const loadingTask = pdfjsLib.getDocument({data: arrayBuffer});
    const pdf = await loadingTask.promise;

    // 获取指定页面
    const page = await pdf.getPage(pageNumber);

    // 获取页面尺寸
    const viewport = page.getViewport({ scale: 1.5 });

    // 创建画布
    const canvas = document.createElement('canvas');
    canvas.width = viewport.width;
    canvas.height = viewport.height;
    const context = canvas.getContext('2d');

    // 渲染页面到画布
    const renderContext = {
      canvasContext: context,
      viewport: viewport
    };
    await page.render(renderContext).promise;

    // 将画布内容转换为 Base64 编码的图片
    const base64Image = canvas.toDataURL('image/png');

    return base64Image;
  } catch (error) {
    console.error('Error converting PDF page to base64 image:', error);
    throw error;
  }
}

// PDF转Word
export async function pdfToWord1(arrayBuffer) {
  try {

    // 加载 PDF 文档
    const loadingTask = pdfjsLib.getDocument({data: arrayBuffer});
    const pdf = await loadingTask.promise;

    // 提取所有页面的文本内容
    let textContent = '';
    for (let pageNumber = 1; pageNumber <= pdf.numPages; pageNumber++) {
      const page = await pdf.getPage(pageNumber);
      const textContentPage = await page.getTextContent();
      textContent += textContentPage.items.map(item => item.str).join(' ') + '\n';
    }

    // console.log(`🚀 ~ pdfToWord ~ textContent:`, textContent)
    // return

    // 将文本内容转换为 Word 文件
    console.log(`🚀 ~ docx ~ textToArrayBuffer(textContent):`, textToArrayBuffer(textContent))
    const docx = await mammoth.convertToHtml({ arrayBuffer: textToArrayBuffer(textContent) }, {
          styleMap: [
              "p[style-name='Section Title'] => h1:fresh",
              "p[style-name='Subsection Title'] => h2:fresh"
          ]
      })
    const wordContent = `
      <!DOCTYPE html>
      <html>
      <head>
        <meta charset="UTF-8">
      </head>
      <body>
        ${docx.value}
      </body>
      </html>
    `;

    // // 将 HTML 内容保存为 Word 文件
    // fs.writeFileSync(wordPath, wordContent, 'utf-8');

    console.log('PDF converted to Word successfully');
  } catch (error) {
    console.error('Error converting PDF to Word:', error);
  }
}


export async function pdfToWord(file) {

  return new Promise((resolve, reject) => {
    try {
      // 读取文件内容
      const fileReader = new FileReader();
      fileReader.onload = async (e) => {
        const pdfBytes = new Uint8Array(e.target.result);

        // 使用 pdfjs-dist 加载 PDF 文档
        const loadingTask = pdfjsLib.getDocument(pdfBytes);
        const pdf = await loadingTask.promise;

        // 获取所有页面
        const pages = [];
        for (let pageNumber = 1; pageNumber <= pdf.numPages; pageNumber++) {
          const page = await pdf.getPage(pageNumber);
          const textContent = await page.getTextContent();
          const text = textContent.items.map(item => item.str).join(' ');
          pages.push(text);
        }

        // 将所有页面的文本合并
        const fullText = pages.join('\n\n');


        resolve(fullText)

        // // 使用 mammoth 将文本转换为 Word 文档
        // const wordBlob = new Blob([fullText], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' });
        // console.log(`🚀 ~ fileReader.onload= ~ wordBlob:`, wordBlob)

        // // 创建下载链接
        // const downloadLink = document.getElementById('downloadLink');
        // downloadLink.href = URL.createObjectURL(wordBlob);
        // downloadLink.download = 'output.docx';
        // downloadLink.style.display = 'block';
      };

      fileReader.readAsArrayBuffer(file);
    } catch (error) {
      console.error('Error converting PDF to Word:', error);
      reject(error)
    }
  })
}